Repository navigation
Conversation
added 9 commits
November 20, 2026 13:10
Keep the legacy Forge listener arrays and Guava ModContainer ABI. Use Forge 7 for native subscriptions and FML-owned lifecycle execution. Include the compatibility fixtures, benchmark sources, and validation notes.
- Align current and legacy channels and preserve callback scopes and access checks. - Reduce managed dispatch and legacy construction overhead and add regression coverage.
… reuse - Revert the unreleased changelog rewording to the branch wording. - Keep an explicit cleared dispatch owner from falling back to the shared controller in Loader.activeModContainer, with a regression test. - Drop the internal Event marker from the channel adapters, dispatch by kind, and document the cancellable factories. - Reuse permission-checked LambdaMetafactory factories for managed annotation registrations.
- Drop the unreleased entry so CHANGELOG.md matches main.
- Accept the Forge 7 Priority byte scale in LegacyEventChannel and map it onto the five legacy buckets. - Add channel subscriptions that omit the group and use the owning mod default group. - Create that group per ModContainer and retire it when FML disables the mod.
- Register discovered subscriber classes under their owning mod and log failures like register(Object). - Track the resulting removal in the mod default group so disabling the mod unregisters them.
Carry the optional-dependency subscriber discovery fallback into SubscriberMethod and cover static and instance registrations.
Ecdcaeb
marked this pull request as draft
November 21, 2026 03:33
Read event method descriptors when reflection cannot link an optional dependency. Keep retiring default groups available for retries and close the FML bus when registration fails or is declined.
Ecdcaeb
marked this pull request as ready for review
November 21, 2026 11:45
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
This PR modernizes Cleanroom's event architecture in three coupled steps while maintaining compatibility with Forge 1.12.2 mods and historical bytecode/reflection contracts:
Eventclasses: RemovesEventSubscriptionTransformerand resolves event shapes, listener lists, and subscriber methods dynamically at runtime.RecordEvent,MutableEvent,InheritableEvent, scopedBusGroups,Priorityconstants, andboolean/alwaysCancelling/MONITORsemantics.BUSworkflow across Forge 7 & Legacy events: Both generations expose symmetricBUSfields, sharebyte Priorityordering, accept a single Forge 7@SubscribeEventannotation (even onprivatemethods!), support whole-class scanning, and automatically retire listeners when a mod is disabled.65.54 ns/opvs181.99 ns/opat 16 listeners with< 0.01 B/opvs~32 B/opallocation, and near-zero (0.011–0.096 B/op) managed owner context overhead.At a Glance: Before vs. After
EventSubscriptionTransformerEventShaperecord/MutableEvent/InheritableEvent+ LegacyEventMyEvent.BUS.subscribe(...)backed by managed per-mod default groupsEventPriorityenum@SubscribeEvent&byte Priorityworks across Forge 7 and Legacyevent.setCanceled(true)boilerplatebooleanreturns,alwaysCancelling = true, &subscribeCancellingon bothpublic(or bytecode-publicized)private/private statichandlers viaMethodHandles.Lookup@Mod.EventBusSubscriber+ defaultSubscriptionGroup+ FML bus)post181.99 ± 26.90 ns/op,~32 B/op65.54 ± 31.34 ns/op(~2.8x faster),< 0.01 B/opArchitecture Overview
flowchart TB subgraph Caller["Mod / Cleanroom Code"] SUB["SubscriptionGroup (Auto / Scoped ModContainer owner)"] AES["@Mod.EventBusSubscriber (Forge 7 + Legacy static discovery)"] F7E["Forge 7 Event (RecordEvent / MutableEvent / InheritableEvent) — public static final EventChannel BUS"] LEGE["Legacy Forge Event (net.minecraftforge.fml...Event) — public static final LegacyEventChannel BUS"] FMLMC["FMLModContainer (@Mod.EventHandler & @Subscribe)"] end subgraph Bridge["Cleanroom Event Bridge (com.cleanroommc.cleanroom.event)"] EC["EventChannel / CancellableEventChannel (BusGroup.DEFAULT default, register / subscribe)"] LEC["LegacyEventChannel (lazy MinecraftForge.EVENT_BUS, Priority mapping, subscribeCancelling)"] CS["ChannelSubscribers (Unified Forge 7 + Legacy Discovery & Shared LMF Factories)"] CTX["ModEventContext (@HideFromUserdev) ThreadLocal Object[2]: AMBIENT_OWNER + DISPATCH_OWNER"] end subgraph Runtimes["Underlying Dispatch Runtimes"] EB7["Forge EventBus 7.0.6 (BusGroup, EventBus, CancellableEventBus)"] LEGB["Legacy EventBus & ListenerList (EventShape cache, EventListenerFactory LMF + fallback)"] GUAVA["FMLThrowingEventBus (Pure Guava + BusGroup disposal on close)"] end F7E --> EC LEGE --> LEC SUB & AES --> EC & LEC & LEGB EC & LEC --> CS EC -->|"owns BusGroup + raw()"| EB7 LEC -->|"uses scope()"| LEGB EC & LEGB & FMLMC -->|"pushDispatchOwner / restoreDispatchOwner"| CTX FMLMC -->|"ModContainer.registerBus"| GUAVA FMLMC -->|"@Mod.EventHandler via ModStateDispatch"| EB7 LoadController -->|"activeContainer + retire defaultGroup on disable"| CTX & SUBWhat It Looks Like
1. Event-Owned
BUSChannels (One Convention Everywhere)Attach
BUSdirectly to the event class—whether it's a sleek Javarecordon EventBus 7 or an existing 1.12.2Event:Available Forge 7 factories (
(Class)forBusGroup.DEFAULT, or(BusGroup, Class)for isolated buses):EventChannel.of(...)/record(...)/mutable(...)/inheritable(...)EventChannel.cancellable(...)/cancellableRecord(...)/cancellableMutable(...)/cancellableInheritable(...)2. Zero-Boilerplate Subscriptions & One Unified
@SubscribeEventDaily mod code doesn't have to manage groups at all—channels default to the active mod's framework-managed
SubscriptionGroup.current(), and automatically retire when the mod is disabled:Or use one Forge 7
@SubscribeEvent(net.minecraftforge.eventbus.api.listener.SubscribeEvent) across both Forge 7 and Legacy events—keeping handlersprivate, usingbooleancancellation returns on legacy cancelable events, and registering whole classes in one call:And existing
@Mod.EventBusSubscriberclasses now automatically discover and retire static Forge 7@SubscribeEventhandlers alongside legacy@SubscribeEventhandlers—zero extra registration code required!3. Temporary Scopes, Guarded Firing & Power-User Escape Hatches
For advanced cases:
LegacyEventChannel.of(AttachCapabilitiesEvent.class).withGenericType(Entity.class)ListenerListlegacy events:LegacyEventChannel.of(CustomBaseEvent.class).withListenerList(CustomBaseEvent.LIST)@SubscribeEventbatch:subs.registerLegacy(MinecraftForge.EVENT_BUS, MethodHandles.lookup(), handler)EventBus.create(MyEvent.BUS.scope(), MyEvent.BUS.eventType())(orCancellableEventBus.create(...)) returns the exact same underlying bus instance aschannel.raw()when callers want direct upstream Forge 7 access with zero owner-wrapping overhead.Performance
Reproducible JMH harnesses live in
module/cleanroom/src/benchmark/java/com/cleanroommc/cleanroom/event/benchmark/(LegacyEventBusBenchmark,LegacyEventBusWorkload,EventChannelBenchmark) withgradle/eventbus-benchmark.gradle.EventShape.RECENT_SHAPES(256-slot weak direct-mapped cache) +Event.isCancelableAndCanceledbitflag fast path keep single-type construction at7.54 ± 0.97 ns/opvs7.08 ± 3.64 ns/op(without bytecode rewriting) and run 16-listener fresh legacy posts2.78xfaster (65.54 ± 31.34 ns/opvs181.99 ± 26.90 ns/op,< 0.01 B/opvs~32 B/op). Zero/one-listener fresh posts trade a few nanoseconds (8.40/15.39 ns/opvs4.62/10.00 ns/op) for zero class-transformation overhead.ModEventContext.OWNER_FRAME(Object[2]) keeps unset-ambient managedEventChanneldispatch allocation near zero (0.011–0.096 B/op), whileChannelSubscribersandEventListenerFactorycache reusableLambdaMetafactoryhidden classes per declaring method rather than spinning a new class per registration.Full JMH numbers & benchmark command (Windows x64, Temurin 25.0.5+8, -Dfml.LogContext=false)
f3e4f5fe)EventChannelCallbackUnder the hood
1. Runtime Legacy EventBus without
EventSubscriptionTransformerEventSubscriptionTransformeris removed fromFMLCorePluginandFoundationTransformerProvider(kept only inside test fixtures for live differential tests).EventShape: ComputesCANCELABLE,HAS_RESULT,VIRTUAL_CANCELLATION, and handwrittensetup()/getListenerList()flags once per class without instantiating the event. A 256-slot weak direct-mapped cache (RECENT_SHAPES) sits in front of the canonicalClassValue<EventShape>underListenerList.REGISTRY_LOCKsoEvent.<init>avoids repeatedClassValuelookups while never retaining mod classloaders.Event: Reads itsEventShapeonce in the constructor and addsEvent.isCancelableAndCanceled(Event)to inspect bitflags directly unlessisCancelable()orisCanceled()was overridden.SubscriberMethod: Replaces transformer publicization withClassValue-cached discovery viaTypeToken. Preserves cross-package package-private ancestor override dispatch (invocationTarget), deduplicates covariant bridges, and gathers declaredprivatesubscribers separately so legacyEventBus.registerskips them whileLookup-backed registration can invoke them.ListenerList: KeepsListenerListInst's historical methods and volatile snapshot arrays, while addingIdentityHashMapreverse indices (registrations/extraRegistrations) forASMEventHandlerandContextSetterEventListenersounregisterand failed-batch rollbacks don't walkallLists.EventListenerFactory: Splits legacy global caching (FACTORIES) from managed registrations (MANAGED_FACTORIES). Managed paths always runcaller.unreflect(method)before creating or hitting a cachedLambdaMetafactoryhidden class (anchored on the subscriber's declaring class viaprivateLookupInwhen module/classloader allow, falling back to an adaptedMethodHandleacross loader/module boundaries).EventBus: Preserves historical reflection targets (listeners,listenerOwners,busID,maxID,ASMEventHandler.subInfo,"ASM: ..."readable descriptions, reflectiveregister(Class, Object, Method, ModContainer)) and legacy per-method failure logging. Exposes@HideFromUserdevmanaged entry points (registerManaged,registerManagedLenient,prepareManagedListeners,prepareLegacySubscribers,addManagedListener,hasManagedListeners,requireCancelable) with atomic prepare-then-install rollback andlisteners.containsKeydeduplication.2. Cleanroom Channel API (
com.cleanroommc.cleanroom.event)EventChannel<E>&CancellableEventChannel<E>: Sealed hierarchy over Forge 7EventBus/CancellableEventBus. Both keepnet.minecraftforge.eventbus.internal.Eventout of source, public ABI, and bytecode—EventChannel.dispatch(E)switches onEventKind(RECORD,MUTABLE,INHERITABLE) and casts only to Forge 7's exported base interfaces, keeping named JPMS modules working cleanly.ChannelSubscribers: Discovers Forge 7@SubscribeEventmethods for exact-channel or whole-class scans across both Forge 7 and LegacyEventsubclasses (voidconsumers,booleancancelling predicates,alwaysCancelling = true, and 2-arg(event, boolean)Priority.MONITORhooks on Forge 7), rejects dual legacy + Forge 7 annotations on a single method, verifiesMethodHandles.Lookupaccess up front, caches LMF factories per class inClassValue, and rolls back atomically on partial failure.LegacyEventChannel<E>: MirrorsEventChannelfor legacyEventsubclasses—including unifiedbyte Prioritymapping,subscribeCancellingpredicates, Forge 7@SubscribeEventsupport,withGenericType,withListenerList, and lazyMinecraftForge.EVENT_BUSresolution sostatic final BUSfields never trigger prematureMinecraftForge.<clinit>.SubscriptionGroup&Subscription: Tracks handles per owningModContainer, provides framework-managed per-mod default groups (current()/defaultGroup(ModContainer)/@HideFromUserdev closeDefaultGroup(ModContainer)/registerDiscovered(...)) guarded against accidental external.close()(UnsupportedOperationException), exposes unified cross-generationregister(Lookup, Object), closes in reverse order, preserves multiple teardown errors as suppressed exceptions, and remains safe to retry after failures.3. FML Lifecycle, Auto-Subscriber Retirement &
ModEventContextFMLThrowingEventBus&FMLModContainer:ModContainer.registerBuskeeps pure Guava delivery (@Subscribe, FIFO reentrancy,DeadEvent,AllowConcurrentEvents).FMLModContainerroutes its@Mod.EventHandlercallbacks onto an owned Forge 7EventBus<ModStateDispatch>viainstallLifecycleHandlers(@HideFromUserdev), which disposes itsBusGroupinsideFMLThrowingEventBus.close().AutomaticEventSubscriber&LoadController: Registers@Mod.EventBusSubscriberstatic legacy + Forge 7@SubscribeEventclasses under the owning mod's defaultSubscriptionGroupand callsSubscriptionGroup.closeDefaultGroup(mod)when disabling or rolling back mods—retiring both legacy and Forge 7 subscribers together.ModEventContext(@HideFromUserdev),Loader,LoadController: Replaces per-post wrapper allocations with a reused thread-localObject[2]slot ([AMBIENT_OWNER, DISPATCH_OWNER]). UsesPUBLISHER(Boolean.FALSE) andNO_OWNER(Boolean.TRUE) sentinels soLoader.activeModContainer()viaModEventContext.activeOwner(modController)honors an explicitsetActiveModContainer(null)inside a callback instead of falling through toLoadController.activeContainer(), whilevolatile LoadController.activeContainerkeeps the loading mod visible to worker threads. Preserves nestedThreadContext("mod")under-Dfml.LogContext=true.Breaking changes & intentional non-compatibility
A few legacy quirks rely on bytecode rewriting or unindexed reflection hacks that aren't worth carrying forward. They fail explicitly instead of silently misbehaving:
IEventListenerinjected via reflection intoEventBus.listeners:ListenerListreverse-indexes standardASMEventHandlerandContextSetterEventListenerregistrations. If a mod reflectively inserts a customIEventListenerdirectly intoEventBus.listeners,EventBus.unregister(target)throwsUnsupportedOperationException("Custom IEventListener entries in EventBus.listeners are unsupported")before mutating anything. Register customIEventListeners directly viaListenerList.register/unregister/unregisterAllinstead.LISTENER_LISTfields: RemovingEventSubscriptionTransformermeansClass.getConstructor()returns only the constructors an event actually declared. Ordinary events register without needing instantiation; handwritten events need a declared accessible constructor for legacyEventBus.register, orLegacyEventChannel.withListenerList(...)for abstract handwritten base events.@Cancelable/@HasResultbelow a handwritten parent override: Annotating a subclass whose parent overridesisCancelable()orhasResult()in Java without declaring a local override throwsIllegalArgumentExceptionnaming the class and property.ListenerListchains: If any class in an inheritance chain overridessetup()orgetListenerList(), every layer in that chain must declare both methods or shape resolution throwsIllegalArgumentException.superhacks:invokespecialhelpers or reflection targeting old transformer-generated members are unsupported; use standard Java overrides and virtual getters.MethodHandles.Lookupon managed paths:EventChannel,LegacyEventChannel, andSubscriptionGroupLookuppaths check caller access before creating/caching LMF factories and never reach inheritedprivatemethods; direct.close()on framework-managed default groups (SubscriptionGroup.current()/defaultGroup(ModContainer)) throwsUnsupportedOperationException. LegacyEventBus.register(Object)still skipsprivatemethods and logs/skips broken individual methods instead of aborting the batch.Full 1.12.2 compatibility behaviors preserved (verified against 7695d38 baseline)
@Cancelableand@Event.HasResult(includingRenderGameOverlayEvent.Pre/PostandConfigChangedEvent.OnConfigChanged), handwrittensuperchains, same-class method overriding same-class annotation, dynamic virtual property getters on the posted instance, independent handwrittenListenerListhierarchies, per-instancegetListenerList()routing, publicListenerList.register/unregister/unregisterAllsnapshot invalidation, abstract child inheritance (and now also direct registration of abstract ordinary events + covariant bridge deduplication).EventPriority, child-before-parent, registration order,receiveCanceleduncancellation,IGenericEventidentity matching,Event.classcatch-all listeners, nestedpost()snapshot isolation, later-slot array mutation visibility, unchecked pass-through & checked exception wrapping, exception context (index,listenersarray, bus, event), equal registration key deduplication, concurrent bus ID/array serialization.EventBus.listeners,listenerOwners,busID,maxID,ASMEventHandler.subInfo, original"ASM: ..."toString(),ListenerListInstlist/rebuild methods, reflectiveEventBus.register(Class, Object, Method, ModContainer), cross-package package-private overriding (SubscriberMethod), interface defaults & diamond inheritance, non-void handlers, separate per-instance receiver binding,IContextSetter, Guava FIFO/reentrancy/DeadEvent/AllowConcurrentEvents, and synchronous NettyFMLEventChannel.fireReadreplies.Tests
All tests passed. and coploit with JEI 4.16.1.302, AppleSkin 1.0.14, Nature's Compass 1.8.5 works well.
EventChannelTest(21) — factories, scopedBusGroup, whole-class Forge 7register(...), cancellation &MONITOR, private/static/instance@SubscribeEventbatches, atomic rollback,ModEventContext&fml.LogContextnesting/exception recoveryLegacyEventBusContractTest(15) — reflection fields (listeners,listenerOwners,subInfo), customIEventListenerUnsupportedOperationException, explicitLookupcapability checks, concurrent list invalidation, named JPMS module checksLegacyEventBusDifferentialTest(13) — differential oracle vs compiled7695d38ahistorical sources + transformersManagedEventBusLifecycleTest(9) — defaultSubscriptionGrouptracking & managed-close guard,@Mod.EventBusSubscriberretirement (legacy + Forge 7) on mod disable, unified cross-generationregister, nesting (Legacy ->EventChannel-> Guava), and handwrittenListenerListchannelsEventBusTest(7) — legacy registration, abnormal return types, reflective 4-argregister, dual-annotation rejection & lenient registration deduplicationLegacyEventChannelTest(6) — lazyMinecraftForge.EVENT_BUS,withGenericType,withListenerList,hasListeners,Prioritybucket mapping,subscribeCancelling, Forge 7@SubscribeEvent& whole-class legacyregisterManagedGuavaEventBusTest(5) — FIFO reentrancy,DeadEvent,AllowConcurrentEvents, exception discards, teardown on closeFMLModLifecycleTest(4) — shared lifecycle events on Forge 7ModStateDispatch, worker-thread visibility,NO_OWNERdispatch clearing, disable cleanup on throwForgeEventBusArtifactSmokeTest(1) — unmodifiedeventbus:7.0.6under FoundationLaunchClassLoaderFMLEventChannelTest(1,isolatedTest) — real NettyEmbeddedChannelfireReadreply handlingChanged Files by Layer
module/cleanroom/src/main/java/com/cleanroommc/cleanroom/event/):package-info.java,EventChannel.java,CancellableEventChannel.java,ChannelSubscribers.java,LegacyEventChannel.java,SubscriptionGroup.java,Subscription.javamodule/forge/src/main/java/net/minecraftforge/fml/common/eventhandler/):Event.java,EventShape.java,SubscriberMethod.java,ListenerList.java,EventListenerFactory.java,EventBus.java,ASMEventHandler.java,IContextSetter.java+ removal fromFMLCorePlugin.java&FoundationTransformerProvider.javaAutomaticEventSubscriber.java,ModEventContext.java,FMLThrowingEventBus.java,FMLModContainer.java,LoadController.java,Loader.javaHistoricalEventBusFixture.java,LegacyEventBusDifferentialTest.java,LegacyEventBusContractTest.java,LegacyDispatchScenarios.java,LegacyMetadataScenarios.java,LegacySubscriberScenarios.java,PackageParent.java,module/forge/src/test/resources/eventbus-baseline/7695d38a.../**,EventChannelTest.java,LegacyEventChannelTest.java,ForgeEventBusArtifactSmoke*.java,FMLModLifecycleTest.java,ManagedEventBusLifecycleTest.java,ManagedGuavaEventBusTest.java,EventBusTest.java,FMLEventChannelTest.java,gradle/eventbus-benchmark.gradle,EventChannelBenchmark.java,LegacyEventBusBenchmark.java,LegacyEventBusWorkload.java